var form = layui.form,
    laydate = layui.laydate,
    upload = layui.upload,
    table = layui.table,
    $ = layui.jquery,
    costCode = getQueryVariable("costCode");

lay('.starttime').each(function(){
    laydate.render({
        elem: this,
        value: new Date(),
    });
});
//表单初始值，修改时调用
if (costCode != "") {
    form.val("editor-form", {
        "registrationnumber": "进入修改",
    })
}



let costDetailData=[];
let depts=[];
let tempId=''
let accs=''
let costFee=[];
let databillCompanys=[]
//收款单位银行名称变量
let dataPayeeBankName;
//收款单位银行账号变量
let dataPayeeBankAccount;
//附件集合
annexData = [];
//收款单位
let dataPays=[];

//币种
let currencyInfo = [];
//美元编码
let usdCode = "";
//美元
let usdName = "";
//美金汇率
let usdRate = "";
//美金对人名币汇率
let rmbRate = "";
//所有用户
let userAll=[];

layer.ready(function () {

    //加载用户
    $.ajax({
        type:"get",
        url:"cost/getAccByDeptCode",
        success:function(data){
            if (data.status==200){
                userAll=data.data;
            }
        }
    });

    //添加
    $.ajax({
        url:"cost/getSelectPrimary",
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        success:function(data){
            if(data.status==200){
                //页面加载获取费用编号
                $("#code").val(data.data.code);
                //页面加载获取收款单位编号名称
                dataPays=data.data.payeeVOS;
                for (let i in dataPays){
                    $("#payeeCode").append("<option value=\"" + dataPays[i].payeeCode + "\">" + dataPays[i].payeeName + "</option>");
                }
                //页面加载获取制单单位编号名称
                databillCompanys=data.data.billCompanyVOS;
                let initCompanyCode;
                let initCompanyName;
                for (let i in databillCompanys){
                    initCompanyCode=databillCompanys[0].companyCode;
                    initCompanyName=databillCompanys[0].companyName
                    if (!isEmpty(databillCompanys[i])){
                        $('#billCompanyCode').append(new Option(databillCompanys[i].companyName, databillCompanys[i].companyCode));
                    }
                }

                $("#billCompanyCode").val(initCompanyCode);
                $("#billCompanyName").val(initCompanyName);
                form.render('select');
            }
        }
    });
    $.ajax({
        url:"cost/getDept",
        success:function(data){
            if(data.status==200){
                depts=data;
            }
        }

    })
    $.ajax({
        url:'cost/getAcc',
        success:function(data){
            if(data.status==200){
                accs=data;
            }
        }
    })
    let LxAndType={};
    LxAndType['type']=5;
    LxAndType['lx']=19;
    $.ajax({
        url:'cost/getCostName',
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(LxAndType),
        success:function(data){
            if(data.status==200){
                costFee=data;
            }
        }
    })


    //获取币种
    $.ajax({
        url:"receivePayment/getCurrencyInfo",
        async:false,
        success:function(data){
            if(data.status == 200){
                currencyInfo = data.data;
                for(let i in data.data){
                    if(data.data[i].englishName == "RMB"){
                        //美元编码
                        usdCode = data.data[i].code;
                        //美元
                        usdName = data.data[i].name;
                        //美元汇率
                        usdRate = data.data[i].exchangeRate;
                        $("#usdRate").val(usdRate);
                    }else if(data.data[i].englishName == "USD"){
                        //获取美金对人名币汇率
                        rmbRate = data.data[i].exchangeRate;
                    }
                    $('#currencyCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                if(usdCode.length > 0){
                    //默认RMB选中
                    $('#currencyCode').val(usdCode);
                    $('#currency').val(usdName);
                    //RMB汇率为1
                    $('#rmbRate').val(1);
                }
                form.render('select');
            }
        }
    });

    //获取当前登陆用户名称
    $.ajax({
        url:"cost/getLoginUserInfo",
        success:function(data){
            if(data.status == 200){
                $("#operatorName").val(data.data.name);
                $("#operatorCode").val(data.data.code);
            }
        }
    });
})
//监听币种下拉框
form.on('select(currencyCode)', function (data) {
    if(data.value === ""){
        return;
    }
    let englishName = getCurrencyInfoByCode(data.value, 1);
    if(englishName == "RMB"){
        //如果选择rmb，则对应rmb汇率为1
        $("#rmbRate").val(1);
        $("#usdRate").val(usdRate);
    }else if(englishName == "USD"){
        //如果选择美元，则对应美金汇率为1
        $("#rmbRate").val(rmbRate);
        $("#usdRate").val(1);
    }else{
        //其它
        let exchangeRate = getCurrencyInfoByCode(data.value, 3);
        $("#usdRate").val(exchangeRate);
        $("#rmbRate").val(rmbRate);
    }
    let name = getCurrencyInfoByCode(data.value, 2);
    $("#currency").val(name);
})

//获取币种信息：code:编码  type(1:获取英文名称 2:获取name 3:获取汇率)
function getCurrencyInfoByCode(code, type){
    for(let i in currencyInfo){
        if(currencyInfo[i].code == code){
            let res = "";
            switch (type) {
                case 1:
                    res = currencyInfo[i].englishName;
                    break;
                case 2:
                    res = currencyInfo[i].name;
                    break;
                case 3:
                    res = currencyInfo[i].exchangeRate;
                    break;
            }
            return res;
        }
    }
    return "";
}

//监听制单公司下拉框
form.on('select(billCompanyCode)', function (data) {
    if(data.value === ""){
        return;
    }
    $("#billCompanyName").val(getInStorePerson(data.value));
})

function getInStorePerson(code){
    for(let i in databillCompanys){
        if(databillCompanys[i].companyCode == code){
            return databillCompanys[i].companyName;
        }
    }
    return "";
}

//监控收款单位下拉框，显示银行名称下拉框
form.on('select(payeeFilter)', function (data) {
    let select_text = data.elem[data.elem.selectedIndex].text;
    $("#inputPayeeName").val(select_text);
    $("#payeeCode").next().find("dl").css({ "display": "none" });
    if(data.value === ""){
        form.render();
        return;
    }

    $('#bankName').empty();
    $('#inputBankName').empty();
    $('#bankAccount').empty();
    $('#inputBankAccount').empty();
    $('#accountName').empty();

    let payeeCode=$("#payeeCode").val();
    if(payeeCode!=null){
        $.ajax({
            url:"cost/getPayeeBankName",
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:payeeCode,
            async:false,
            success:function(data){
                if(data.status==200){
                    let array=[];//存放去重之后的银行名称
                    let bankNameArray=[];//临时存放全部的银行名称
                    for (let i in data.data) {
                        bankNameArray.push(data.data[i].bankName);
                    }
                    for (let i in bankNameArray) {
                        if (array.indexOf(bankNameArray[i])==-1){
                            array.push(bankNameArray[i]);
                        }
                    }
                    let bankName0;
                    for (let i in array) {
                        bankName0=array[0];
                        $("#bankName").append("<option class='bankNameOption' value=\"" + array[i]+ "\">" + array[i] + "</option>");
                    }
                    $('#inputBankName').val(bankName0);
                }
                form.render('select');
            }
        });
        let payeeReq={};
        let bankName=$("#inputBankName").val();
        payeeReq['bankName']=bankName;
        payeeReq['payeeCode']=payeeCode;


        $.ajax({
            url:"cost/getPayeeBankAccount",
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:JSON.stringify(payeeReq),
            async:false,
            success:function(data){
                if(data.status==200){
                    $("#bankAccount").empty();
                    let bankAccount0;
                    for (let i in data.data) {
                        bankAccount0=data.data[0].bankAccount
                        $("#bankAccount").append("<option class='bankAccountOption'  value=\"" + data.data[i].bankAccount + "\">" + data.data[i].bankAccount + "</option>");
                    }
                    $('#inputBankAccount').val(bankAccount0);
                }
                form.render('select');
            }
        });


        //获取银行账号名称
        let bankAccount=$("#inputBankAccount").val();
        $.ajax({
            url:"cost/getPayeeBankAccountName?payeeCode="+payeeCode+"&bankAccount="+bankAccount,
            type:"GET",
            async:false,
            success:function(data){
                if(data.status==200){
                    $('#accountName').val(data.data);
                }
            }
        })



    }

});
//监控银行名称下拉框，显示银行账号下拉框
form.on('select(bankNameFilter)', function (data) {
    let select_text = data.elem[data.elem.selectedIndex].text;
    $("#inputBankName").val(select_text);
    $("#bankName").next().find("dl").css({ "display": "none" });

    $('#accountName').empty();

    let bankName=$("#inputBankName").val();
    let payeeCode=$("#payeeCode").val();
    let payeeReq={};
    payeeReq['bankName']=bankName;
    payeeReq['payeeCode']=payeeCode;
    if(bankName!=null){
        $.ajax({
            url:"cost/getPayeeBankAccount",
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:JSON.stringify(payeeReq),
            async:false,
            success:function(res){
                if(res.status==200){
                    $('#bankAccount').empty();
                    let bankAccount0;
                    for (let i in res.data) {
                        bankAccount0=res.data[0].bankAccount
                        $('#bankAccount').append(new Option(res.data[i].bankAccount, res.data[i].bankAccount));
                    }
                    $('#inputBankAccount').val(bankAccount0);
                }
                form.render('select');
            }
        })

        //获取银行账号名称
        let bankAccount=$("#inputBankAccount").val();
        $.ajax({
            url:"cost/getPayeeBankAccountName?payeeCode="+payeeCode+"&bankAccount="+bankAccount,
            type:"GET",
            async:false,
            success:function(data){
                if(data.status==200){
                    $('#accountName').val(data.data);
                }
            }
        })

    }
});
form.on('select(bankAccountFilter)', function (data) {
    let select_text = data.elem[data.elem.selectedIndex].text;
    $("#inputBankAccount").val(select_text);
    // $("#bankAccount").next().find("dl").css({ "display": "none" });
    if(data.value === ""){
        form.render();
        return;
    }
    let bankAccount=$("#inputBankAccount").val();
    let payeeCode=$("#payeeCode").val();
    if(bankAccount !=null && payeeCode !=null ){
        //获取银行账号名称
        let bankAccount=$("#inputBankAccount").val();
        $.ajax({
            url:"cost/getPayeeBankAccountName?payeeCode="+payeeCode+"&bankAccount="+bankAccount,
            type:"GET",
            async:false,
            success:function(data){
                if(data.status==200){
                    $('#accountName').val(data.data);
                }
            }
        })
    }


});
$('#inputPayeeName').bind('input propertychange', function () {
    let value = $("#inputPayeeName").val();
    $("#payeeCode").val(value);
    form.render();
    $("#payeeCode").next().find("dl").css({ "display": "block" });
    let dl = $("#payeeCode").next().find("dl").children();
    let j = -1;
    for (var i = 0; i < dl.length; i++) {
        if (dl[i].innerHTML.indexOf(value) <= -1) {
            dl[i].style.display = "none";
            j++;
        }
        if (j == dl.length-1) {
            $("#payeeCode").next().find("dl").css({ "display": "none" });
        }
    }

});

$('#inputBankName').bind('input propertychange', function () {
    let value = $("#inputBankName").val();
    $("#bankName").val(value);
    form.render();
    $("#bankName").next().find("dl").css({ "display": "block" });
    let dl = $("#bankName").next().find("dl").children();
    let j = -1;
    for (var i = 0; i < dl.length; i++) {
        if (dl[i].innerHTML.indexOf(value) <= -1) {
            dl[i].style.display = "none";
            j++;
        }
        if (j == dl.length-1) {
            $("#bankName").next().find("dl").css({ "display": "none" });
        }
    }

});

$('#inputBankAccount').bind('input propertychange', function () {
    let value = $("#inputBankAccount").val();
    $("#bankAccount").val(value);
    form.render();
    $("#bankAccount").next().find("dl").css({ "display": "block" });
    let dl = $("#bankAccount").next().find("dl").children();
    let j = -1;
    for (var i = 0; i < dl.length; i++) {
        if (dl[i].innerHTML.indexOf(value) <= -1) {
            dl[i].style.display = "none";
            j++;
        }
        if (j == dl.length-1) {
            $("#bankAccount").next().find("dl").css({ "display": "none" });
        }
    }

});
//当选中核算部门时请求后台得到核算人员集合
let personnel=[];
table.render({
    elem: '#maininformation',
    id: 'maininformationtableid',
    data: costDetailData,
    toolbar: '#maininformationtoolbar',
    cols: [[
        {checkbox: true, fixed: true},
        {field:'invoiceCode', title:'发票号码'},
        {field: 'increaseCode',  title: '增票号', edit: 'text',templet: function (d) {
                if (isEmpty(d.increaseCode)){
                    return '无'
                }else {
                    return d.increaseCode
                }
            }},
        {field: 'contractNo', width: 120, title: '外销合同号'},
        {field:'stockNoStr', title:'采购合同号',width: 120, edit: 'text'},
        {field: 'feeName',  title: '费用名称', templet: '#costofnameselect'},
        {field: 'applicationAmount',  title: '申请金额', edit: 'text'},
        {field: 'salesmanName',  title: '承担人员', edit: 'text'},
        {field: 'salesmanCode',  hide:true},
        {field:'departmentName', title:'核算部门',  templet:'#departmentSelect'},
        {field:'accountantName', title:'核算人员',  templet:'#accountantSelect'},
        {field: 'specialDesc',  title: '特殊备注', edit: 'text'},
        {field: 'costClassification',  title: '费用归类', edit: 'text'},
        {field: 'billDate',  title: '单据日期', edit: 'text'},

    ]],
    done: function (res, curr, count) {
        $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
        $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
        for (let i in depts.data) {
            $('.deptClass').append("<option value=\"" + depts.data[i].departmentCode+ "\">" + depts.data[i].departmentName+ "</option>");
        }
        for (let j in costFee.data) {
            $('.costNameClass').append("<option value=\"" + costFee.data[j].feeCode+ "\">" + costFee.data[j].feeName+ "</option>");
        }

        let sum=new BigNumber(0.00);
        let amount=new BigNumber(0.00);
        for (var i = 0; i < res.data.length; i++) {
            if(!isNumber(res.data[i].applicationAmount)){
                amount=new BigNumber(0).toFixed(2);
            }else {
                amount=new BigNumber(res.data[i].applicationAmount).toFixed(2);
            }
            sum=sum.plus(amount);


            //临时id从子页面中带过来的
             tempId = res.data[i].tempId;
             $("#costName_" + tempId).val(res.data[i].feeCode);
             $("#dept_" + tempId).val(res.data[i].departmentCode);
             let tempDepartmentCode=res.data[i].departmentCode;
            if (!isEmpty(tempDepartmentCode)){
                let deptByUser=[];
                for (let j in userAll) {
                    if (userAll[j].deptCode === tempDepartmentCode){
                        deptByUser.push(userAll[j]);
                    }
                }
                for (let j in deptByUser) {
                    $("#acc_" + tempId).append(new Option(deptByUser[j].accountantName, deptByUser[j].accountantCode));
                }
                $("#acc_" + tempId).val(res.data[i].accountantCode);
                for (let j in deptByUser) {
                    if (deptByUser[j].accountantCode===res.data[i].accountantCode){
                        res.data[i].accountantName=deptByUser[j].accountantName;
                    }
                }
            }

            //当承担人员不为空 核算人员为空时，将核算部门显示成承担人员所在部门，核算人员显示成承担人员
            if (!isEmpty(res.data[i].salesmanCode) && isEmpty(res.data[i].accountantCode)){//承担人员不为空 核算人员为空
                for (let j in userAll) {
                    if (userAll[j].accountantCode === res.data[i].salesmanCode){
                        //添加核算部门
                        $("#dept_" + tempId).val(userAll[j].deptCode);
                        res.data[i].departmentName=userAll[j].departmentName;
                        res.data[i].departmentCode=userAll[j].deptCode;

                        if (!isEmpty(res.data[i].departmentCode)){
                            $.ajax({
                                type:"get",
                                async:false,
                                url:"cost/getAccByDeptCode?deptCode="+res.data[i].departmentCode,
                                success:function(data){
                                    personnel=data.data
                                    for(let i in data.data){
                                        $("#acc_" + tempId).append(new Option(data.data[i].accountantName,data.data[i].accountantCode));
                                    }
                                    form.render('select');
                                }
                            });
                        }

                        //添加核算人员
                        $("#acc_" + tempId).val(userAll[j].accountantCode);
                        res.data[i].accountantName=userAll[j].accountantName;
                        res.data[i].accountantCode=userAll[j].accountantCode;
                        break;
                    }
                }
            }

        }
        $('#totalAmount').val(sum.toFixed(2));
        form.render('select');

    },

    height: 540,
    page:false,
    limit: Number.MAX_VALUE,
});
function isEmpty(val) {
    if(val == "" || val == null || val == undefined){
        return true;
    }else {
        return false;
    }
}

form.on("select(costofnameselect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["maininformationtableid"];
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["feeCode"] = data.value;
            for(let i in costFee.data){
                if(data.value==costFee.data[i].feeCode){
                    tabledata[index]["feeName"] = costFee.data[i].feeName;
                }

            }

        }
    });
});

//监听部门表下拉框
form.on("select(departmentSelect_filter)", function(data){
    let deptCode;
    var elem = data.othis.parents("tr");//获取当前列的上一级标签<table>
    var dataindex = elem.attr("data-index");//获取当前列的序号(0，1，2，3，4，5)
    var tabledata = table.cache["maininformationtableid"];
    let nowTempId=tabledata[dataindex].tempId;
    $('#acc_'+nowTempId).empty();
    $.each(tabledata,function(index,value){
        //当选择中行的序号等于表格中的序号时，给下拉框的文本框赋值
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["departmentCode"] = data.value;//当选择这个下拉框时，这个下拉框才会有这个字段
            deptCode=data.value;
            for(let i in depts.data){
                if(data.value==depts.data[i].departmentCode){
                    tabledata[index]["departmentName"] = depts.data[i].departmentName;
                }

            }

        }
    });
    $.ajax({
        type:"get",
        async:false,
        url:"cost/getAccByDeptCode?deptCode="+deptCode,
        success:function(res){
            personnel=res.data;
            for(let i in res.data){
                $("#acc_" + nowTempId).append("<option value=\"" + res.data[i].accountantCode+ "\">" + res.data[i].accountantName + "</option>");

            }
            if (res.data.length>0){
                $("#acc_" + nowTempId).val(res.data[0].accountantCode);
                tabledata[dataindex]['accountantCode']=res.data[0].accountantCode;
                tabledata[dataindex]['accountantName']=res.data[0].accountantName;
            }

            form.render('select');
        }
    });
});


form.on("select(accountantSelect_filter)", function(data){
    var elem = data.othis.parents("tr");
    var dataindex = elem.attr("data-index");
    var tabledata = table.cache["maininformationtableid"];

    //循环从部门那里获得的人员集合，并赋值到下拉框
    $.each(tabledata,function(index,value){
        if(value.LAY_TABLE_INDEX==dataindex){
            tabledata[index]["accountantCode"] = data.value;
            for(let i in personnel){
                if(data.value==personnel[i].accountantCode){
                    tabledata[index]["accountantName"] = personnel[i].accountantName;
                }

            }
        }
    });

});

//监听提交
form.on('submit(form-element)', function (data) {
    var indexsl = 0;
    var maininformationdata = table.cache["maininformationtableid"];
    $.each(maininformationdata,function(index,value){
        if(typeof (maininformationdata[index]["increaseCode"])== "undefined" || maininformationdata[index]["increaseCode"]==""){
            layer.msg("费用明细表第"+(index+1)+"条增票号不能为空");
            indexsl++;
            return false;
        }else if(typeof (maininformationdata[index]["feeName"])== "undefined" || maininformationdata[index]["feeName"]==""){
            layer.msg("费用明细表第"+(index+1)+"条费用名称不能为空");
            indexsl++;
            return false;
        }else if(typeof (maininformationdata[index]["applicationAmount"])== "undefined" || maininformationdata[index]["applicationAmount"]==""){
            layer.msg("费用明细表第"+(index+1)+"条申请金额不能为空");
            indexsl++;
            return false;
        }else if(typeof (maininformationdata[index]["accountantName"])== "undefined" || maininformationdata[index]["accountantName"]==""){
            layer.msg("费用明细表第"+(index+1)+"条核算人员不能为空");
            indexsl++;
            return false;
        }else if(typeof (maininformationdata[index]["departmentName"])== "undefined" || maininformationdata[index]["departmentName"]==""){
            layer.msg("费用明细表第"+(index+1)+"条核算部门不能为空");
            indexsl++;
            return false;
        }
    });
    if(indexsl == 0){
        let datas=data.field;
        datas["annexReqs"] = table.cache["attachmenttableid"];
        datas['costDetails']=maininformationdata
        //1：保存，2：提交
        datas['insertStatus']='1';
        //1：新增，2：修改
        datas['setType']='1';

        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:JSON.stringify(datas),
            url:"cost/add/register",
            success:function (res) {
                if(res.status==200){

                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/Money/cost.jsp");
                        parent.intab("views/jsp/Money/cost.jsp","费用")
                        parent.detab("views/jsp/Money/tpl/registerdirectcharges.jsp"+(costCode==''?'':'?costCode='+costCode));
                    },1000);
                    return false;
                }else {
                    layer.msg(res.data, {icon: 6});
                    return false;
                }

            }
        });

    }

});
form.on('submit(form-element2)', function (data) {
    var indexsl = 0;
    var maininformationdata = table.cache["maininformationtableid"];
    $.each(maininformationdata,function(index,value){
        if(typeof (maininformationdata[index]["increaseCode"])== "undefined" || maininformationdata[index]["increaseCode"]==""){
            layer.msg("费用明细表第"+(index+1)+"条增票号不能为空");
            indexsl++;
            return false;
        }else if(typeof (maininformationdata[index]["feeCode"])== "undefined" || maininformationdata[index]["feeCode"]==""){
            layer.msg("费用明细表第"+(index+1)+"条费用名称不能为空");
            indexsl++;
            return false;
        }else if(typeof (maininformationdata[index]["applicationAmount"])== "undefined" || maininformationdata[index]["applicationAmount"]==""){
            layer.msg("费用明细表第"+(index+1)+"条申请金额不能为空");
            indexsl++;
            return false;
        }else if(typeof (maininformationdata[index]["accountantName"])== "undefined" || maininformationdata[index]["accountantName"]==""){
            layer.msg("费用明细表第"+(index+1)+"条核算人员不能为空");
            indexsl++;
            return false;
        }else if(typeof (maininformationdata[index]["departmentName"])== "undefined" || maininformationdata[index]["departmentName"]==""){
            layer.msg("费用明细表第"+(index+1)+"条核算部门不能为空");
            indexsl++;
            return false;
        }
    });
    if(indexsl == 0){
        let datas=data.field;
        datas["annexReqs"] = table.cache["attachmenttableid"];
        datas['costDetails']=maininformationdata
        //1：保存，2：提交
        datas['insertStatus']='2';
        //1：新增，2：修改
        datas['setType']='1';

        let resAddCostId=null;
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:JSON.stringify(datas),
            url:"cost/add/register",
            async:false,
            success:function (res) {
                if(res.status==200){
                    resAddCostId=res.data;

                    // let costBpmId=startPurchaseProcess(resAddCostId);
                    // update(resAddCostId,2,'提交审批',costBpmId);
                    // let taskId=getTasKId(costBpmId);
                    // commit(taskId);

                    layer.msg("提交审批成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/Money/cost.jsp");
                        parent.intab("views/jsp/Money/cost.jsp","费用")
                        parent.detab("views/jsp/Money/tpl/registerdirectcharges.jsp"+(costCode==''?'':'?costCode='+costCode));
                    },1000);
                    return false;
                }else {
                    layer.msg(res.data, {icon: 6});
                    return false;
                }

            }
        });
    }
});
//审批流开始，获取流程ID
function startPurchaseProcess(bid) {
    let res;
    $.ajax({
        type : 'get',
        data:{"processDefId":'cost',"bid":bid,"variables":null},
        url:'process/startProcess',
        dataType:"json",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                res=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return res;
}
//boxStatus 1 草稿 2 待批  3:已批 4 完成 5 垃圾
//costBpmStatus审批状态  0：未审核 1：审批中 2：审核完成。提交审批设置初始状态为0
//更新费用的状态
function update(id,status,titleName,costBpmId) {
    let tf = false;
    let msgInfo = "";
    let dataJson = {
        "id":id,
        "status":status,
        "costBpmId":costBpmId,
        "costBpmStatus":"1",
    };
    $.ajax({
        type: 'POST',
        data: JSON.stringify(dataJson),
        url: 'cost/updateCostStatusByCostId',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = true;
                msgInfo = titleName+"成功!"
                table.reload('maininformationtableid');
            }else{
                msgInfo = titleName+"失败!"
            }
        },
        error: function (data) {
            msgInfo = titleName+"异常!"
        }
    });
    layer.msg(msgInfo);
    return tf;
}
//根据流程ID获取任务ID
function getTasKId(instanceId) {
    let res;
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:instanceId,
        async:false,
        url:"cost/getTasKId",
        success : function (da) {
            if(da.status==200 ){
                res=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return res;
}
//第一次提交时自动通过，直接到下一个审批人节点
function commit(taskId) {
    $.ajax({
        type : 'get'
        ,data:{"taskId":taskId,"variables":null,"activityId":null,"comment":null},
        url:'cost/commitProcess',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                layer.msg("提交成功");
                close();
            }else{
                layer.msg("提交失败!");
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });

}

function isNumber(val) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}
table.on('edit(maininformationtable)',function (obj) {
    let sum=new BigNumber(0.00);
    let amount=new BigNumber(0.00);
    var old=$(this).prev().text();//旧值
    //判断数据类型 ,,,,,,,
    if((obj.field== "applicationAmount" || obj.field== "applicationAmount")&&!isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        return;
    }
    if (obj.field== "applicationAmount"){
        var tabledata =table.cache["maininformationtableid"];
        $.each(tabledata,function(index,value){
            if(!isNumber(value.applicationAmount)){
                amount=new BigNumber(0).toFixed(2);
            }else {
                amount=new BigNumber(value.applicationAmount).toFixed(2);
            }
            sum=sum.plus(amount);
        });
        $('#totalAmount').val(sum.toFixed(2));
    }

});

table.on('toolbar(maininformationtable)', function (obj) {


    var checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'importinvoice':
            layer.open({
                type: 2,
                area: ['1488px', '800px'],
                content: 'views/jsp/Money/tpl/importinvoice.jsp'
            });
            break;
        case 'importcontract':
            layer.open({
                type: 2,
                area: ['1488px', '800px'],
                content: 'views/jsp/Money/tpl/importcontract.jsp'
            });
            break;
        case 'importResourceSamples':
            layer.open({
                type: 2,
                area: ['1488px', '800px'],
                content: 'views/jsp/Money/tpl/importResourceSamples.jsp'
            });
            break;
        case 'del':
            let num=checkStatus.data['id']=1
            var data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
                delList.push(n.tempId);
                num++;
            });
            if(delList!=''){
                layer.confirm('确定删除所选项吗？',function (index) {
                    var cbList = table.cache["maininformationtableid"];
                    for(var i = 0;i<cbList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined"&&item == cbList[i].tempId) {
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("maininformationtableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };



});

//---附件
table.render({
    elem: '#attachment'
    , toolbar: '#attachmenttoolbar'
    , data:annexData
    , cols: [[
        {field: 'fileName', title: '文件名', fixed: true,event: "fileName"}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
});
let uploadListIns = upload.render({
    elem: '#uploadfile'
    , url: 'transfer/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                data[i].fileUrl=res.data[i].ftpPath+"/"+res.data[i].fileName;
                annexData.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexData}); //点击关闭刷新表格
                }
            });
            break;
    }
    ;
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?',
            confirmInfo(3,5), function (index) {
                obj.del();
                var id = data.id;
                for (var i = 0; i < annexData.length; i++) {
                    if (annexData[i].id == id) {
                        annexData.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                        i--; // 如果不减，将漏掉一个元素
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
                table.reload('attachmenttableid', {data:annexData}); //ajax删除成功之后刷新表格
            });
    }else if(obj.event === 'fileName'){//点击名称，在线预览
        onLineFile(obj.data.fileUrl);
    }
});
//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//---操作日志
let data2=[];
    table.render({
        elem: '#otherwarehouselog'
        , data: data2
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });